<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Rubik Ultimate Framework
 * @version 	: 1.1
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 *
 * Created on	:  Jun 15, 2008
 *
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );
session_start();
RCoreImporter::cls( "mvc.AbstractController" );
// Import class to validator
RPluginImporter::cls('authenticate.FrontAuthenticateFinder');
RPluginImporter::cls('authenticate.BackAuthenticateFinder');
/**
 * The controller for Authenticate application
 *
 */
class AuthenticateController extends AbstractController {
	var $_model;
	/**
	 * Default display
	 *
	 */
	function display() {
		// Check for login
		$msg = SysRequest::getVar ( "msg" );
		$templatePath = SYS_CUR_TMPL_URL;
		$checkLog = $this->_checkLogin ();
		if ($checkLog === true) {
			//			RubikHelper::debugPrePrint('ccccc');
			$this->_redirect_url ();
			return;
		}
		$username = SysLanguage::_('USERNAME');
		$password = SysLanguage::_('PASSWORD');
		$register = SysLanguage::_('REGISTER');
		$forgot = SysLanguage::_('FORGOT');
		$login_form = SysLanguage::_('LOGIN_FORM');
		$login = SysLanguage::_('LOGIN');
		SysResponse::appendPageTitle("Login");


		$msg .= $checkLog;
		if (! SysAuthenticate::isLogged() ) {
			if (SystemSite::isBackEnd()) {
				$tmpl = SysApplication::loadTemplate ( "back/login" );
				@eval ( '$tmpl = "' . $tmpl . "\";" );
				echo $tmpl;
			} else {
				$fogotpassword = new SiteResource('users', 'forgot');
				$fogotpassword = $fogotpassword->getLink();

				//				require SysApplication::getTemplatePath( "front/login" );
				@eval ( 'echo "' . SysApplication::loadTemplate( "front/login" ) . "\";" );
			}
		} else {
			$this->_redirect_url ();
		}
	}


	/*	function login(){
	 //		RubikHelper::debugPrePrint($_POST ['username']);
	 //		RubikHelper::debugPrePrint($_POST ['password']);
		$checkLog = $this->_checkLogin ();
		if ($checkLog === true) {
		//			RubikHelper::debugPrePrint('aaaa');
		$this->_redirect_url ();
		return;
		} else {
		//			RubikHelper::debugPrePrint('bbbb');
		$this->setRedirect(SystemSite::urlRoute('?app=authenticate&act=display'));
		//			$this->setRedirectToFunction('display');
		}
		}
		*/
	/*
	 * Register an account
	 *
	 * */
	function register(){
		if (SysRequest::getVar('msg')){
			echo "<div class=\"message\"> ".SysRequest::getVar('msg')." </div>";
		}


		SysApplication::importModelCls('AuthenticateModel');
		$this->_model = new AuthenticateModel();
		$model = $this->_model;
		$root_path = SYS_ROOT_URL;
		$registerDTO = new UserDTO();
		$registerDTO->bind($_POST);
		$registerDTO->group_id="2";

		$getRe_pass = SysRequest::getVar('re_password', NULL, 'POST');
		$getUsername = $registerDTO->username;
		$getPass = $registerDTO->password;
		$getName = $registerDTO->name;
		$getAddress = $registerDTO->address;
		$getPhone = $registerDTO->phone;
		$getEmail = $registerDTO->email;

		//----------so sanh pass va re-pass-----------------------------
		if ($getPass != $getRe_pass){
			$mess_rePass = SysLanguage::_('REG_RETYPE_PASS');
			eval('echo "'.SysApplication::loadTemplate('front/register').'";');
			return false;
		}

		//---------kiem tra ten dang nhap co ton tai chua--------------
		$sql = "SELECT COUNT(*) FROM user WHERE username LIKE  '$getUsername'";
		$comp = SysDatabase::loadResult($sql);
		if($comp==1){
			echo "<div class=\"message\"> ".SysLanguage::_('REG_EXIST_USERNAME')." </div>";
		}
		//---kiem tra da nhap username va password chua-----------
		if ($_POST['register']){
			if(empty($getUsername)){
				//				$msg = "banh mi";
				//				$this->setRedirectToCurrentFunction($msg);
				echo "<div class=\"message\"> ".SysLanguage::_('REG_USERNAME')." </div>";
			}
			if(empty($getPass)){
				echo "<div class=\"message\"> ".SysLanguage::_('REG_PASS')." </div>";
				eval('echo "'.SysApplication::loadTemplate('front/register').'";');
				return false;
			}
		}
		$result = $model->saveUserDTO($registerDTO);



		//-------thogn bao dang ki ko thanh cong-------------
		if($result==FALSE && $_POST['register']){
		}
		//-------thogn bao dang ki  thanh cong-------------
		else if($_POST['register']){
			echo "<div class=\"message\">".SysLanguage::_('REG_SUCCESS')."</div>";
			$getPass = '';
			$getName = '';
			$getAddress ='';
			$getPhone = '';
			$getEmail = '';
		}

		//		RubikHelper::debugPrePrint($username);
		//		//die();

		eval('echo "'.SysApplication::loadTemplate('front/register').'";');

	}
	/**
	 * Redirect to the URL
	 *
	 */
	function _redirect_url() {
		$redirect_url = base64_decode ( SysRequest::getVar ( 'redirect_url' ) );
		if (empty ( $redirect_url )) {
			if (SystemSite::isBackEnd()) {
				$redirect_url = SYS_ADMIN_URL;
			} else {
				//				$userProfiles = new SiteResource('users', 'profiles');
				//				$redirect_url = $userProfiles->getLink();
				$redirect_url = SYS_ROOT_URL;
			}
		}
		$this->setRedirect ( $redirect_url );
	}

	/**
	 * Check for login
	 *
	 */
	function _checkLogin() {
		if (empty ( $_POST ['username'] ) && empty ( $_POST ['password'] )) {
			return "";
		}
		if (SystemSite::isBackEnd()) {
			$isCorrect = SysAuthenticate::backLogin($_POST ['username'], $_POST ['password']);
		}
		// TODO for front-end
		if(SystemSite::isFrontEnd()) {
			$isCorrect = SysAuthenticate::frontLogin($_POST ['username'], $_POST ['password']);
			$_SESSION['username'] = $_POST ['username'];
			
		}

		// you may check the access group here
		if (! $isCorrect) {
			$msg = SysLanguage::_( "WRONG_USER_PASS" );
			return $msg;
		}
		return true;
	}

	/**
	 * Logout
	 */
	function logout() {
		SysAuthenticate::logout();
		if(SystemSite::isFrontEnd()) {
			unset($_SESSION['birthday']);
			unset($_SESSION['username']);
			unset($_SESSION['phone']);
			unset($_SESSION['email']);
			unset($_SESSION['address']);
			unset($_SESSION['company']);
			unset($_SESSION['_RU_AuthenticateObjback']);
			$this->setRedirect ( SYS_ROOT_URL );
		} else {
			$this->_redirect_url ();
		}
	}
	function userAccount(){
		$root_path = SYS_ROOT_URL;
		$link = "{$root_path}bds/DangtinBDS";
		if ($_POST['dangtin']){
			$this->setRedirect($link);
		}		
		SysApplication::importModelCls('AuthenticateModel');
		$this->_model = new AuthenticateModel();
		$model = $this->_model;
		$session = SysAuthenticate::getAuthenticateObject();
		$sess_username = $session->username;
		$sql = "SELECT * FROM user WHERE username = '$sess_username'";
		$result = SysDatabase::loadObject($sql);
		$getId = $result->user_id;
		$getUsername = $result->username;
		$getPass =$result->password;
		$getName = $result->name;
		$getAddress = $result->address;
		$getPhone = $result->phone;
		$getEmail = $result->email;
		
		//----------so sanh pass va re-pass-----------------------------

		if ($_POST['edit']){
			$getRe_pass = SysRequest::getVar('re_password', NULL, 'POST');
			$getPassCmp = SysRequest::getVar('password', NULL, 'POST');
			if ($getPassCmp != $getRe_pass && $_POST['edit'] && !empty($getRe_pass)){
				$mess_rePass = SysLanguage::_('REG_RETYPE_PASS');
				eval('echo "'.SysApplication::loadTemplate('front/userAccount').'";');
				return false;
			}			
//			$editDTO = new UserDTO();
//			$editDTO->resetToNull();
//			$editDTO->bind($_POST);
//			$editDTO->user_id = $getId;
//			$editDTO->username = $getUsername;
//			$editDTO->password = 
//			RubikHelper::debugPrePrint($editDTO);
//			$saveEdit = $model->saveUserDTO($editDTO);
			if(!empty($_POST['password'])){
				$pass = md5($_POST['password']);
				$sql = "UPDATE user SET password='$pass' ,
										name='{$_POST['name']}',
										address = '{$_POST['address']}',
										phone = '{$_POST['phone']}',
										email = '{$_POST['email']}'
										WHERE user_id = '$getId'";
				SysDatabase::execute($sql);
			}else {
				$sql = "UPDATE user SET name='{$_POST['name']}',
										address = '{$_POST['address']}',
										phone = '{$_POST['phone']}',
										email = '{$_POST['email']}'
										WHERE user_id = '$getId'";
				SysDatabase::execute($sql);
			}
		}

		if ($_POST['edit']){
			$getName = $_POST['name'];
			$getAddress = $_POST['address'];
			$getPhone = $_POST['phone'];
			$getEmail = $_POST['email'];
			echo "<div class=\"message\">".SysLanguage::_('REG_EDIT')."</div>";
		}
		eval('echo "'.SysApplication::loadTemplate('front/userAccount').'";');
		
	}
}
